<template>
  <view class="container house_resource">

    <view class="search_house">
      <view class="search_keys">
        <up-input
            v-model="searchParams.keyword"
            placeholder="搜索关键字，支持房源名称"
            prefixIcon="search"
            shape="circle"
            prefixIconStyle="font-size: 22px;color: #909399"
            @input="filterList"
            @change="filterList"
            :clearable="true"
        ></up-input>
<!--        <view v-if="filterType" class="filter_icons">-->
<!--          <tm-icon fontSize="24" name="iconfont icon-shaixuanyixuan" color="#165DFF" style="transform: rotate(90deg);"></tm-icon>-->
<!--          <view>筛选</view>-->
<!--        </view>-->
      </view>
      <view class="search_main">
        <view :class="['search_item', 'search_region', filterType === 1 ? 'selected' : '']" @click="() => switchFilter(1)">
          <text class="region_text">区域</text>
          <tm-icon fontSize="24" name="iconfont icon-youjiantou" color="#8091A4" style="transform: rotate(90deg);"></tm-icon>
        </view>
        <view :class="['search_item', 'search_region', filterType === 2 ? 'selected' : '']"  @click="() => switchFilter(2)">
          <text class="region_text">项目</text>
          <tm-icon fontSize="24" name="iconfont icon-youjiantou" color="#8091A4" style="transform: rotate(90deg);"></tm-icon>
        </view>
        <view :class="['search_item', 'search_region', filterType === 3 ? 'selected' : '']"  @click="() => switchFilter(3)">
          <text class="region_text">更多筛选</text>
          <tm-icon fontSize="24" name="iconfont icon-youjiantou" color="#8091A4" style="transform: rotate(90deg);"></tm-icon>
        </view>
      </view>
      <view class="filter_section">
<!--      搜素区域 -->
        <view v-if="filterType === 1" class="area_list">
          <view class="area_section_left">
  <!--          <view @click="() => selectCity({name: '全部', id: 'all'})" :class="['section_item', searchParams.city === 'all' ? 'selected' : '']" >全部</view>-->
            <view v-for="(item, i) in areaList" @click="() => selectCity(item)" :class="['section_item', searchParams.city === item.id ? 'selected' : '']" :key="i">{{item.name}}</view>
          </view>
          <view class="area_section_right">
  <!--          <view @click="() => selectCountry({name: '全部', id: 'all'})" :class="['section_item', searchParams.district === 'all' ? 'selected' : '']">全部</view>-->
            <view v-for="(item,i) in countyLevelData" @click="() => selectCountry(item)" :class="['section_item', searchParams.district === item.id ? 'selected' : '']" :key="i">{{item.name}}</view>
          </view>
        </view>

  <!--       筛选项目  -->
        <view v-if="filterType === 2" class="project_area">
            <view v-for="item in projectList" :class="['project_item', searchParams.community_id === item.id ? 'selected' : '']" :key="item.id" @click="() => selectProject(item)">
              {{item.name}}
            </view>
        </view>
  <!--      更多筛选 -->
        <view v-if="filterType === 3" class="more_filter">
          <view class="more_filter_item">
            <view class="more_item_label">面积</view>
            <view class="more_item_value">
              <view class="mj_item" @click="() => switchArea({min_area: 0, max_area: 300})">300㎡以下</view>
              <view class="mj_item" @click="() => switchArea({min_area: 300, max_area: 600})">300㎡~600㎡</view>
              <view class="mj_item" @click="() => switchArea({min_area: 600, max_area: 1000})">600㎡~1000㎡</view>
              <view class="mj_item" @click="() => switchArea({min_area: 1000, max_area: 1500})">1000㎡~1500㎡</view>
              <view class="mj_input">
                <up-input
                    placeholder="最小值"
                    v-model="searchParams.min_area"
                    customStyle="width: 60px;"
                    placeholderStyle="font-size:12px;"
                ></up-input>
              </view>
              <view>至</view>
              <view class="mj_input">
                <up-input
                    placeholder="最大值"
                    v-model="searchParams.max_area"
                    customStyle="width: 60px;"
                    placeholderStyle="font-size:12px;"
                ></up-input>
              </view>
  <!--            <view class="more_sure_btn">确认</view>-->
            </view>
          </view>
          <view class="more_filter_item">
            <view class="more_item_label">租金</view>
            <view class="more_item_value">
              <view class="mj_item" @click="() => switchPrice({min_price: 0, max_price: 2})">2元以下</view>
              <view class="mj_item" @click="() => switchPrice({min_price: 2, max_price: 7})">2~3元</view>
              <view class="mj_item" @click="() => switchPrice({min_price: 3, max_price: 4})">3~4元</view>
              <view class="mj_item" @click="() => switchPrice({min_price: 4, max_price: 5})">4~5元</view>
              <view class="mj_item" @click="() => switchPrice({min_price: 5, max_price: 6})">5~6元</view>
              <view class="mj_item" @click="() => switchPrice({min_price: 6, max_price: ''})">6元以上</view>
              <view class="mj_input">
                <up-input
                    placeholder="最小值"
                    v-model="searchParams.min_price"
                    customStyle="width: 60px;"
                    placeholderStyle="font-size:12px;"
                ></up-input>
              </view>
              <view>至</view>
              <view class="mj_input">
                <up-input
                    placeholder="最大值"
                    v-model="searchParams.max_price"
                    customStyle="width: 60px;"
                    placeholderStyle="font-size:12px;"
                ></up-input>
              </view>
  <!--            <view class="more_sure_btn">确认</view>-->
            </view>
          </view>
          <view class="more_filter_item">
            <view class="more_item_label">装修</view>
            <view class="more_item_value">
              <view v-for="(item, i) in standsList" :key="item.val" :class="['mj_item', item.checked ? 'selected' : '']" @click="() => switchSubmitWay(item, i)">{{item.name}}</view>
            </view>
          </view>
          <view class="more_filter_item more_filter_specail">
            <view class="more_item_label">楼层</view>
            <view class="more_item_value">
              <view class="mj_input">
                <up-input
                    placeholder="最小值"
                    v-model="searchParams.min_floor"
                    customStyle="width: 60px;"
                    placeholderStyle="font-size:12px;"
                ></up-input>
              </view>
              <view>至</view>
              <view class="mj_input">
                <up-input
                    placeholder="最大值"
                    v-model="searchParams.max_floot"
                    customStyle="width: 60px;"
                    placeholderStyle="font-size:12px;"
                ></up-input>
              </view>
  <!--            <view class="more_sure_btn">确认</view>-->
            </view>
          </view>
        </view>
        <view v-if="filterType" class="zs_filter_btns">
          <up-button type="primary" shape="circle" customStyle="width: 160px;" plain text="重置" @click="handleReset"></up-button>
          <up-button type="primary" shape="circle" customStyle="width: 160px;" text="搜索" @click="handleSearch"></up-button>
        </view>
      </view>
    </view>
    <view class="house_list">
      <view v-for="(item, i) in houseListData" :class="['house_item', item.checked ? 'selected' : '']" :key="i" @click="() => selectHouse(item, i)">
        <image v-if="item.checked" class="select_img" src="@/static/img/house_checked.png"/>

          <view class="house_item_head">
            <view class="house_item_img">
              <tm-image preview :src="`${ASSETS_HOST}${item.house_resource_imgs}`" :width="210" :height="210"></tm-image>
              <view class="house_img_bg">{{matchDictionaryName(houseTypeOptions, item.type)}}</view>
            </view>
            <view class="house_item_info">
              <!--              促销图片  todo 加判断-->
              <image class="discount_img" v-if="item.promotion_label === '2'" src="@/static/img/hot.png"/>
              <image class="discount_img" v-if="item.promotion_label === '3'" src="@/static/img/new.png"></image>
              <image class="discount_img" v-if="item.promotion_label === '1'" src="@/static/img/discount.png"></image>
              <view class="house_info_name">{{item.name}}</view>
              <view class="house_info_site">
                <tm-icon fontSize="24" name="iconfont icon-zukeduan-xiangmu" color="#8091A4"></tm-icon>
                <text class="info_site_item">{{item.city_text}}</text>
                <text class="info_site_item">{{item.district_text}}</text>
                <text class="info_site_item info_site_address">{{item.address}}</text>
              </view>
              <view class="house_info_tag">
                <tm-tag v-for="(cItem, i) in item.around_config_text" text :shadow="0" color="#4A76F7" size="m" :label="item.name"></tm-tag>
              </view>
              <view class="house_info_area">
                <tm-icon fontSize="24" name="iconfont icon-mianji" color="#999999"></tm-icon>
                <view class="area_num">{{item.rental_area}}㎡</view>
                <view class="area_price">{{item.pre_lease_price}}</view>
                <view class="area_price">{{item.price_unit_text}}</view>
              </view>
            </view>
          </view>

      </view>
    </view>

    <view class="cus_footer_btn">
      <up-button type="primary" shape="circle" :text="`确认(${curSelectedHouse.length})`" @click="submitData"></up-button>
    </view>
  </view>
</template>
<script setup lang="ts">

import {ref, reactive} from "vue";
import {getClientHouseList, houseCheckArea, houseAndProject, deliveryStandard} from "@/api_request/api";
import {onLoad, onReachBottom} from '@dcloudio/uni-app'
import {ASSETS_HOST} from '@/config';
import {matchDictionaryName} from '@/utils/utils'
import {houseTypeOptions} from '@/utils/dictionary'
import {each} from 'lodash'

//单选标记
const selectOne = ref(0)
//添加跟进记录页面，调过来选择标记
const fllowRec = ref(0)
const houseListData = ref<any>([])
const isLoading = ref<boolean>(false)

const pageNum = ref<number>(1)
const pageSize = ref<number>(10)
const total = ref<number>(0)

// 筛选类型  区域 1   项目 2 更多  3  默认 0  都不显示
const filterType = ref<any>(0)

const areaList = ref<any>([])

const standsList = ref<any>([])
const projectList = ref<any>([])
const countyLevelData = ref<any>([])
const searchParams = reactive<any>({
  city: '', //市
  district: '', //区
  community_id: '',
  min_area: "", //最小面积
  max_area: "", //最大面积
  min_price: "", //最低价格
  max_price: "", //最高价格
  min_floor: "", //最低楼层
  max_floot: "", //最高楼层
  submit_list: [], //交付方式
  keyword: "",
})
const curSelectedHouse = ref<any>([])
const selectHouse = (item, i) => {
  const __selecteds = [...curSelectedHouse.value]
  if(!item.checked) {
  //   add
    if(selectOne.value){
      __selecteds.length = 0
      __selecteds.push(item)
    }else{
      __selecteds.push(item)
    }
  } else {
    //  reduce
    const index = __selecteds.findIndex(cItem => cItem.id === item.id)
    if(index !== -1) {
      __selecteds.splice(index, 1)
    }
  }
  curSelectedHouse.value = __selecteds
  item.checked = !item.checked
  const __list = [...houseListData.value]
  if(selectOne.value){
     __list.forEach(ele=>{if(ele.id != item.id) {ele.checked = false}})
  }
  __list[i] = item
  houseListData.value = __list
}
const switchFilter = (type) => {
  filterType.value = type
}
const submitData = () => {
  // curSelectedHouse.value  传走  即选中的 房源
  if(fllowRec){
    uni.setStorageSync("selectHourseForFollowRec",curSelectedHouse.value);
  }else{
    uni.setStorageSync("selectHourseAtSelectPage",curSelectedHouse.value);
  }
  uni.navigateBack()
}

const selectCity = (item) => {
  searchParams.city = item.id
  if(item.id === 'all') {
    const list:any[] = []
    console.log('jp======(areaList.value',areaList.value)
    each(areaList.value, (city) =>{
      if(city.id !== 'all') {
        list.push(...city.children)
      }
    })
    console.log('jp======list',list)
    countyLevelData.value = list
    return
  }
  countyLevelData.value = item.children || []
  // countyLevelData.value.unshift({
  //   id: 'all',
  //   name: '全部'
  // })
}
const switchArea = (data) => {
  searchParams.min_area = data.min_area
  searchParams.max_area = data.max_area
}
const switchPrice = (data) => {
  searchParams.min_price = data.min_price
  searchParams.max_price = data.max_price
}
const switchSubmitWay = (item, i) => {
  item.checked = !item.checked
  const __list = [...standsList.value]
  __list[i] = item
  searchParams.submit_list = __list
}
const selectCountry = (item) => {
  searchParams.district = item.id
}
const selectProject = (item) => {
  searchParams.community_id = item.id
}
const initHouseList = (type?) => {
  isLoading.value = true
  const params = {
    page_num: pageNum.value,
    page_size: pageSize.value,
    ...searchParams
  }
  getClientHouseList(params).then(res =>{
    console.log('jp======房源列表',res)
    if(type) {
      const  houseList = [...houseListData.value]
      houseList.push(...res.data.list)
      houseListData.value = houseList
    } else {
      houseListData.value = res.data.list
    }

    total.value = res.data.total
    isLoading.value = false
  })
}

const handleDeepData = (obj) => {
  console.log('jp======obj',obj)
  const list: any[] = []
  for(const key in obj) {
    const item = obj[key]
    const cItem: any = {
      id: key,
      name: item.name
    }
    if(Object.keys(item.children).length) {
      cItem.children = handleDeepData(item.children)
    }
    list.push(cItem)
  }
  console.log('jp======list',list)
  return list
}
const timer = ref<any>(null)
const filterList = (val) => {
  console.log('jp======e',val)
  // searchParams.keyword()
  timer.value && clearTimeout(timer.value)
  timer.value = setTimeout(() => {
    console.log('jp======1111',)
    initHouseList()
  }, 500)

}
const handleReset = () => {
  searchParams.value = {
    city: '', //市
    district: '', //区
    community_id: '',
    min_area: "", //最小面积
    max_area: "", //最大面积
    min_price: "", //最低价格
    max_price: "", //最高价格
    submit_list: [], //交付方式
    keyword: "",
  }
}
const handleSearch = () =>{
  initHouseList()
}
onLoad((options) => {
  console.log("options.....",options)
  if(options?.selectOne === '1'){
    selectOne.value = options.selectOne
  }
  //是否是添加跟进记录页面跳转过来选择房源
  if (options?.fllowRec === '1') {
    fllowRec.value = 1
  }

  initHouseList();
//   房源查询
  houseCheckArea({app_id: 123}).then(res => {
    console.log('jp=====区域=',res)
    const __list: any[] = []
    for(const key in res.data) {
      const item = res.data[key]
      console.log('jp======item',item)
      let cItem: any = {}
      for(const i in item.children){
        const curItem = item.children[i]
        cItem.id = i
        cItem.name = curItem.name
        if(Object.keys(curItem.children).length) {
          cItem.children = handleDeepData(curItem.children)
        }
      }
      __list.push(cItem)
    }
    console.log('jp=====__list=',__list)
    areaList.value = __list
    areaList.value.unshift({
      id: 'all',
      name: '全部'
    })
  })
//   项目查询
  houseAndProject({}).then(res=> {
    console.log('jp=====项目=',res)
    projectList.value = res.data
    projectList.value.unshift({id: 'all',label: '全部'})
  })
//  交付标准
  deliveryStandard({}).then(res => {
    console.log('jp======交付标准',res)
    standsList.value = res.data
  })
})
onReachBottom(() => {
  if(isLoading.value) return
  if(houseListData.value?.length === total.value) {
    return
  } else {
    pageNum.value +=1
    initHouseList('reachBottom')
  }
})
</script>

<style lang="less" scoped>

.house_resource{
  .house_list{
    padding: 0 10px;
  }


}
</style>